import VueRouter from 'vue-router';
import store from './store';

const routes = require
    .context('@/pages', true, /page\.vue$/, 'lazy')
    .keys()
    .map((url) => url.replace(/^\.\//, '').replace(/\.page\.vue$/, ''))
    .map((pathName) => {
        return {
            path: `/${pathName}`,
            name: pathName,
            component: () => import(/* webpackChunkName: "[request]" */ `@/pages/${pathName}.page.vue`),
        };
    });

const router = new VueRouter({
    mode: 'hash',
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        } else {
            return { x: 0, y: 0 };
        }
    },
});

router.beforeEach((to, from, next) => {
    if (to.path !== '/account/login' && !store?.state?.user?.userId) {
        next({ path: '/account/login' });
        return;
    }
    next();
});

export default router;
